<?php
/*
Copyright (C) 2011  Benjamin Marchand

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

uses('model' . DS . 'connection_manager');

class InstallerController extends Controller {
	var $name = 'Installer';
	var $uses = array();
	var $components = array('RequestHandler','Session');
	var $helpers = array('Html','Javascript','Session','Js' => array('jquery'));
	//var	$database = 'temp';
	var $database = 'bukkitadmin';
	
	function beforeFilter() {     
		// check if installation file exist
		if (file_exists(APP.'tmp'.DS.'install.log'))
		{
			echo APP.'tmp'.DS.'install.log exist, you cannot install anymore';		
			die();
			}   
	}
	
	function beforeRender() {
		$this->layout ='install';
		$this->set('title_for_layout', 'Webukkit Installer');		
	}
	
	function index() {
		// We check if tmp directory AND subdir is writable
		$path = APP.'tmp'.DS;
		clearstatcache();
		if ($this->is_removeable($path))
		{
			$messages[] = array('image'=>'check-success.png','message'=>'The '.$path.' directory is writable, correct!');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error ! The '.$path.' directory AND subdirectories must be writable!');
		}
		// We check if config directory is writable
		//$path = APP.'config'.DS.'database.php';
		$path = APP.'config'.DS;
		if (is_writable($path))
		{
			$messages[] = array('image'=>'check-success.png','message'=>'The file '.$path.' is writable, correct!');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error ! The file '.$path.' must be writable!');
		}
		// Check json_decode function
		if (function_exists("json_decode"))
		{
			$messages[] = array('image'=>'check-success.png','message'=>'Functions json_decode/encode exists, correct!');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error ! Functions json_decode/encode not exists!');
		}
		//We check if safe mode is enabled or not
		if (ini_get('safe_mode'))
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Warning ! Safe mode activated, the backup of plugins files will not be possible.');
		}
		else
		{
			$messages[] = array('image'=>'check-success.png','message'=>'Safe mode desactivated, correct!');

		}
		$this->set('messages',$messages);
	}
	
	// Check if dir AND subdir are writable
	function is_removeable($dir)
	{
		$folder = opendir($dir);
		while($file = readdir( $folder ))
			if($file != '.' && $file != '..' &&
		(is_dir($dir."/".$file) && !is_writable($dir."/".$file) ||
		(is_dir($dir."/".$file) && !$this->is_removeable($dir."/".$file))))
		{
			closedir($dir);
			return false;
		}
		if (!is_string($dir)) closedir($dir);
		return true;
	}
	
	function createtable()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$prefix = $this->Session->read('sqldatasource.prefix');
		$db = ConnectionManager::getDataSource('default');
		$success = TRUE;
		$data = file_get_contents(ROOT.DS.'sql'.DS.'structure.sql');
		if (!empty($prefix))
		{
			$data = str_replace("`items`", "`".$prefix."items`", $data);
			$data = str_replace("`mctemplateplugins`", "`".$prefix."mctemplateplugins`", $data);
			$data = str_replace("`users`", "`".$prefix."users`", $data);
			$data = str_replace("`mcgroups`", "`".$prefix."mcgroups`", $data);
			$data = str_replace("`mcrights`", "`".$prefix."mcrights`", $data);
			$data = str_replace("`mcusers`", "`".$prefix."mcusers`", $data);
			$data = str_replace("`settings`", "`".$prefix."settings`", $data);
		}
		if ($this->__runSQLdata($db,$data))
		{
			$messages[] = array('image'=>'check-success.png','message'=>'Tables created !');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error during the creation of tables ! (maybe insufficient permissions ?)');
		};
		$this->set('messages',$messages);
		$this->render('/elements/message');
	}
	
	function createdata()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$prefix = $this->Session->read('sqldatasource.prefix');
		$db = ConnectionManager::getDataSource('default');
//		$db = ConnectionManager::create('temp',$this->data);
		$user = file_get_contents(ROOT.DS.'sql'.DS.'user.sql');
		$items = file_get_contents(ROOT.DS.'sql'.DS.'items.sql');
		$mctemplateplugins = file_get_contents(ROOT.DS.'sql'.DS.'mctemplateplugins.sql');
		$data = $user.$items.$mctemplateplugins;
		if (!empty($prefix))
		{
			$data = str_replace("`items`", "`".$prefix."items`", $data);
			$data = str_replace("`mctemplateplugins`", "`".$prefix."mctemplateplugins`", $data);
			$data = str_replace("`users`", "`".$prefix."users`", $data);
		}
		
		if ($this->__runSQLdata($db,$data))
		{
			$messages[] = array('image'=>'check-success.png','message'=>'Data created !');
			file_put_contents(APP.'tmp'.DS.'install.log','ok');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error during the creation of data ! (maybe data already exit ?');
		};
		$this->set('messages',$messages);
		$this->render('/elements/message');
	}

	function createdatabase()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$this->data['host']=$this->Session->read('sqldatasource.host');
		$this->data['login']=$this->Session->read('sqldatasource.login');
		$this->data['password']=$this->Session->read('sqldatasource.password');
		$this->data['database']=$this->Session->read('sqldatasource.database');
		if (empty($this->data['database']))
		{
		$this->data['driver'] = 'mysql';
		$this->data['persistent'] = false;
		$db = ConnectionManager::create('temp',$this->data);
		if ($this->__runSQLfile($db,ROOT.DS.'sql'.DS.'base.sql'))
		{
			$this->Session->write('sqldatasource.database',$this->data['database']);
			$messages[] = array('image'=>'check-success.png','message'=>'Database created !');
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'Error during the creation of database ! (maybe insufficient permissions ?)');
			};
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'You don\'t need to create database, you have already one ! (if you want to create a database, the field \'database\' must be empty)');
		}
		$this->set('messages',$messages);
		$this->render('/elements/message');
	}
	
	function createconfigfile()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		if ($this->Session->check('sqldatasource.host') && $this->Session->check('sqldatasource.login'))
		{
			$name = 'default';
			$host = $this->Session->read('sqldatasource.host');
			$login = $this->Session->read('sqldatasource.login');
			$password = $this->Session->read('sqldatasource.password');
			$database = $this->Session->read('sqldatasource.database');
			$prefix = $this->Session->read('sqldatasource.prefix');
			$driver = 'mysql';
			$persistent = 'false';
			if (empty($database)) $database = $this->database;
			$out = "<?php\n";
			$out .= "class DATABASE_CONFIG {\n\n";		
				$out .= "\tvar \${$name} = array(\n";
				$out .= "\t\t'driver' => '{$driver}',\n";
				$out .= "\t\t'persistent' => {$persistent},\n";
				$out .= "\t\t'host' => '{$host}',\n";
				$out .= "\t\t'login' => '{$login}',\n";
				$out .= "\t\t'password' => '{$password}',\n";
				$out .= "\t\t'database' => '{$database}',\n";
				$out .= "\t\t'prefix' => '{$prefix}',\n";
				$out .= "\t);\n";
				$out .= "}\n";
			$out .= "?>";
			$filename = APP.DS.'config'.DS.'database.php';
			if (file_put_contents($filename,$out))
			{
				$messages[] = array('image'=>'check-success.png','message'=>'Config file created !');
			}
			else
			{
				$messages[] = array('image'=>'clear_icon.png','message'=>'Error during the creation of Config file ! (maybe insufficient permissions ?');
			}
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>'You must define an host and a login for database access!');
		}
		$this->set('messages',$messages);
		$this->render('/elements/message');
		
	}
	
	function checkConnection()
	{
		$this->autoRender = false;
		$this->Session->write('sqldatasource.host',$this->data['host']);
		$this->Session->write('sqldatasource.login',$this->data['login']);
		$this->Session->write('sqldatasource.password',$this->data['password']);
		$this->Session->write('sqldatasource.database',$this->data['database']);
		$this->Session->write('sqldatasource.prefix',$this->data['prefix']);
		$this->data['driver'] = 'mysql';
		$this->data['persistent'] = false;
		$config = array('driver' => 'mysql',
                          'persistent' => false,
                          'host' => $this->data['host'],
                          'login' => $this->data['login'],
                          'password' => $this->data['password'],
                          'database' => $this->data['database']);

		$db = ConnectionManager::create('temp',$config);
		if(!empty($db))
		{
			if (!empty($this->data['database']))
			{
				if ($db->connect())
				{
					echo json_encode(array('code'=>true,'html'=>'<img src="/img/check-success.png" style="vertical-align:middle;padding-right:10px;">Success !'));
				}
				else
				echo json_encode(array('code'=>false,'html'=>'<img src="/img/clear_icon.png" style="vertical-align:middle;padding-right:10px;">Connexion failed !'));
			}
			else
			{
				if ($db->query("SELECT USER();"))
				{
					echo json_encode(array('code'=>true,'html'=>'<img src="/img/check-success.png" style="vertical-align:middle;padding-right:10px;">Success !'));
				}
				else
				echo json_encode(array('code'=>false,'html'=>'<img src="/img/clear_icon.png" style="vertical-align:middle;padding-right:10px;">Connexion failed !'));
			}
		}
		else
		echo json_encode(array('code'=>false,'html'=>'<img src="/img/clear_icon.png" style="vertical-align:middle;padding-right:10px;">Error in the database engine (no MySQL ?) !'));
	}
	
	private function __runSQLfile($db, $fileName) {
		$success = true;
		$statements = file_get_contents($fileName);
		$statements = explode(';', $statements);
		foreach ($statements as $statement) {
			if (trim($statement) != '') {
				//				file_put_contents('c:\temp\bukkit.log',$db->query($statement),FILE_APPEND);
				if (!$db->query($statement))
					$success = false;
			}
		}
		return $success;
	}
	private function __runSQLdata($db, $data) {
		$success = true;
		$statements = explode(';', $data);
		foreach ($statements as $statement) {
			if (trim($statement) != '') {
				if (!$db->query($statement))
					$success = false;
			}
		}
		return $success;
	}
}
?>